import React, {
  useRef,
  useState,
  useImperativeHandle,
  forwardRef,
} from "react";
import { Descriptions } from "antd";
import type { DescriptionProps, DescInstance, DescItem } from "./typing";

// 转发ref以支持实例方法
const Description = forwardRef<DescInstance, DescriptionProps>((props, ref) => {
  // 状态管理：使用useState存储动态props
  const [innerProps, setInnerProps] = useState<DescriptionProps>(props);
  // 合并外部传入的props和内部状态props
  const mergedProps = { ...innerProps, ...props };
  const {
    schema,
    data,
    column = 2,
    bordered = true,
    contentStyle,
    labelStyle,
    size = "default",
    ...descriptionsProps
  } = mergedProps;

  // 通过useImperativeHandle暴露实例方法
  useImperativeHandle(
    ref,
    () => ({
      setDescProps: (newProps) => {
        setInnerProps((prev) => ({ ...prev, ...newProps }));
      },
    }),
    []
  );

  // 渲染标签（参考示例代码）
  const renderLabel = ({ label, labelMinWidth }: DescItem) => {
    if (!labelMinWidth || !labelStyle) {
      return label;
    }

    const labelStyles: React.CSSProperties = {
      minWidth: `${labelMinWidth}px`,
    };
    return <div style={labelMinWidth ? labelStyles : labelStyle}>{label}</div>;
  };

  // 渲染单个描述项
  const renderDescriptionItem = (item: DescItem) => {
    const { label, field, span, show, render, contentMinWidth } = item;
    const value = data ? data[field] : undefined;

    // 条件显示逻辑
    if (show && !show(data)) return null;

    // 获取内容（参考示例代码）
    const getContent = () => {
      return render ? render(value, data) : value;
    };

    // 定义 content 函数
    const content = () => {
      if (!contentMinWidth) {
        return getContent();
      }
      const contentStyles: React.CSSProperties = {
        minWidth: `${contentMinWidth}px`,
      };
      return <div style={contentStyles}>{getContent()}</div>;
    };

    return (
      <Descriptions.Item
        key={field}
        label={renderLabel(item)}
        span={span}
        styles={{
          label: { ...labelStyle }, // 控制 label 样式
          content: { ...contentStyle }, // 控制 content 样式
        }}
      >
        {content()}
        {/* // 调用函数并使用其返回值 */}
      </Descriptions.Item>
    );
  };
  // ... existing code ...

  console.log(labelStyle, contentStyle);

  return (
    <Descriptions
      column={column}
      bordered={bordered}
      size={size}
      {...descriptionsProps}
    >
      {schema?.map((item) => renderDescriptionItem(item))}
    </Descriptions>
  );
});

Description.displayName = "Description";

export default Description;
